﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using DevExpress.Utils.Menu;
using DevExpress.XtraEditors;
using Marmat.Foundation;
using Marmat.FrameWork;

namespace Marmat.Template.WinForm
{

    /// <summary>
    /// 标准的查询界面模块。
    /// </summary>
    public partial class ViewForm : Marmat.Forms.Form, Marmat.Foundation.IViewForm, INotification
    {

        #region 构造函数
        /// <summary>
        /// 构建实例。
        /// </summary>
        public ViewForm()
        {
            InitializeComponent();
        }
        #endregion

        #region"字段"
        /// <summary>
        /// 控制器
        /// </summary>
        private IViewFormRoute viewRoute;

        /// <summary>
        /// 当前嵌入的用户面板。
        /// </summary>
        private System.Windows.Forms.Control panel;
        /// <summary>
        /// 导出按钮实例
        /// </summary>
        private DXMenuItem exportButton;

        /// <summary>
        ///  搜索控件
        /// </summary>
        private ISearchControl searchControl;

        /// <summary>
        /// 当前执行批量的按钮。
        /// </summary>
        private IButtonItem batchButton;

        /// <summary>
        /// 批量操作的面板支持。
        /// </summary>
        private IViewFormPanelBatchAction batchPane;
        #endregion

        /// <summary>
        /// 搜索数据
        /// </summary>
        private void LoadData()
        {
            Foundation.IViewFormController controller = this.viewRoute.GetController();
            if (controller is IViewFormPagination pagination)
            {
                int count = pagination.Load(this.searchControl?.Value.ToString(), pageControl1.LoadPage, pageControl1.LoadTop, null);
                pageControl1.TotalCount = count;
            }
            else
            {
                controller.Load(this.searchControl?.Value.ToString());
            }
        }

        /// <summary>
        /// 窗体是否打开。
        /// </summary>
        bool is_show = false;

        /// <summary>
        /// 窗体打开时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ViewForm_Load(object sender, EventArgs e)
        {
            this.is_show = true;
            this.RefreshLayoutUI();
            this.createButton.Text = Marmat.Template.WinForm.Localization.ViewForm.CreateButtonCaption;

            // 如果已经加载过数据，则不再初始加载。
            Timer timer = new Timer();
            timer.Interval = 1;
            timer.Tick += this.timer1_Tick;
            timer.Enabled = true;
        }

        /// <summary>
        /// 创建按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void createButton_Click(object sender, EventArgs e)
        {
            this.CreateEvent();
        }

        /// <summary>
        /// 创建
        /// </summary>
        public void CreateEvent()
        {
            Foundation.IViewFormController controller = this.viewRoute.GetController();
            controller.CreateEvent();
        }

        /// <summary>
        /// 初始化窗体
        /// 生成动作、打印、筛选的下拉列表
        /// </summary>
        private void InitializeForm()
        {
            Foundation.IViewFormController controller = this.viewRoute.GetController();
            var panel = this.viewRoute.GetViewPanel();

            #region "扩展按钮的构建"

            if (controller is IViewFormExpandButton expandButton)
            {
                var buttonCollection = expandButton.GetExpandButtonCollection();
                foreach (var item in buttonCollection)
                {
                    var button = new DevExpress.XtraEditors.SimpleButton();
                    button.ImageOptions.Image = item.Icon;
                    button.Text = item.Caption ?? item.Name;
                    button.Name = item.Name;
                    button.Click += delegate (object sender, EventArgs e) { expandButton.ButtonClick(item); };
                    this.flowLayoutPanel1.Controls.Add(button);
                }
            }
            #endregion

            #region "分页UI的构建"
            // 如果实现了分页接口，则根据条件开启分页控件,。
            if (controller is IViewFormPagination pagination)
            {
                this.pageControl1.Visible = pagination.Visible;
                this.pageControl1.LoadTop = pagination.PageSize;
            }
            #endregion

            #region "动作及导出功能的UI构建"
            List<(IButtonItem, Action)> actionCollection = new List<(IButtonItem, Action)>();
            if (controller is IAction action)
            {
                foreach (var item in action.GetActionCollection())
                {
                    actionCollection.Add((item, () => action.Execute(item)));
                }
            }

            // 根据特性动态配置动作列表。
            var methods = controller.GetType().GetMethods().ToList();
            methods.ForEach(method =>
            {
                var actionAttribute = method.GetCustomAttribute<Marmat.Foundation.ActionAttribute>();
                if (actionAttribute is not null && method.GetParameters().Length == 0)
                {
                    bool is_permission = true;
                    foreach (var attribute in method.GetCustomAttributes())
                    {
                        if (attribute is IPermissionAttribute permission)
                        {
                            if (!permission.Verify())
                            {
                                is_permission = false;
                                break;
                            }
                        }
                    }
                    if (is_permission)
                    {
                        ButtonItem item = new ButtonItem(actionAttribute.Name, actionAttribute.Text);
                        actionCollection.Add((item, () => method.Invoke(controller, null)));
                    }
                }
            });

            //导出按钮
            if (controller is IExport export)
            {
                ButtonItem item = new ButtonItem("导出", "导出");
                actionCollection.Add((item, () =>
                {
                    IExportForm exportForm = SystemCommand.GetService<IExportForm>();
                    if (exportForm is not null)
                        exportForm.ShowDialog(export, "数据");
                    else
                        throw new NullReferenceException($"没有配置 {typeof(IExportForm).FullName} 服务。");
                }
                ));
            }
            if (this.actionButton.DropDownControl is null)
                this.actionButton.DropDownControl = new DXPopupMenu();
            if (this.actionButton.DropDownControl is DXPopupMenu dropDownControl)
            {
                dropDownControl.Items.Clear();
                foreach (var pair in actionCollection)
                {
                    var item = pair.Item1;
                    DXMenuItem button = new DXMenuItem();
                    button.Caption = string.IsNullOrEmpty(item.Caption) ? item.Name : item.Caption;
                    button.Enabled = item.Enabled;
                    if (item.Icon != null)
                        button.ImageOptions.Image = item.Icon;
                    button.Click += delegate (object _, EventArgs __) { pair.Item2.Invoke(); };
                    dropDownControl.Items.Add(button);
                }
            }
            this.actionButton.Visible = actionCollection.Count > 0;
            this.actionButton.Enabled = actionCollection.Select(x => x.Item1).ToList().Exists(x => x.Enabled);
            #endregion

            #region"打印UI的构建"
            DXPopupMenu batchCollection = new DXPopupMenu();
            if (panel is IViewFormPanelBatchAction viewPanelBatch)
            {
                this.batchPane = viewPanelBatch;
                List<IButtonItem> items = new List<IButtonItem>();
                if (controller is IViewFormBatchAction batchAction)
                    items.AddRange(batchAction.GetBatchActionCollection());

                foreach (var item in items)
                {
                    DXMenuItem button = new DXMenuItem();
                    button.Caption = item.Caption ?? item.Name;
                    button.Click += delegate (object sender, EventArgs e) { this.OpenBatchOperation(item); };
                    batchCollection.Items.Add(button);
                }
                //if (controller is IReport report)
                //{
                //    foreach (var item in report.GetReportCollection())
                //    {
                //        DXMenuItem button = new DXMenuItem();
                //        button.Caption = item.Caption;
                //        button.Click += delegate (object sender, EventArgs e)
                //        {
                //            IReportObject reportObject = Marmat.FrameWork.SystemCommand.GetService<IReportObject>();
                //            reportObject.Load(item.Name);

                //            ReportCancelEventArgs args = new ReportCancelEventArgs(reportObject);
                //            report.Print(args);
                //            if (!args.Cancel)
                //                reportObject.Prepare();
                //        };
                //        batchCollection.Items.Add(button);
                //    }
                //}
                batchCollection.Visible = true;
                this.dropDownButton4.Visible = items.Count > 0;
                this.dropDownButton4.DropDownControl = batchCollection;
            }

            #endregion

            // 暂时不公开
            //DXMenuItem customButton = new DXMenuItem();
            //customButton.Caption = "添加自定义筛选";
            //customButton.BeginGroup = true;
            //customButton.ImageOptions.Image = Properties.Resources.SearchControl_filter;
            //customButton.Click += this.CustomButton_Click;
            //Searchs.Items.Add(customButton);

            DXPopupMenu groups = new DXPopupMenu();
            DXPopupMenu collect = new DXPopupMenu();
            this.dropDownButton2.DropDownControl = groups;
            this.dropDownButton3.DropDownControl = collect;

            this.dropDownButton2.Visible = groups.Items.Count > 0;
            this.dropDownButton3.Visible = collect.Items.Count > 0;
        }


        /// <summary>
        /// 刷新布局UI
        /// </summary>
        private void RefreshLayoutUI()
        {
            this.panel2.Height = panel2.Controls.OfType<Control>().Where(x => x.Visible).Count() > 0 ? 39 : 0;
        }

        /// <summary>
        /// 筛选按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, EventArgs e)
        {
            //if (sender is DevExpress.Utils.Menu.DXMenuItem button)
            //{
            //    if (button.Tag is SearchControlGroup group)
            //    {
            //        this.searchControl.Value.Add(group.Name);
            //        //if (this.searchControl is ISearchControlSuperaddition superaddition)
            //        //    superaddition.Superaddition(group);
            //    }
            //}
        }

        /// <summary>
        /// 按钮的点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dropDownButton1_Click(object sender, EventArgs e)
        {
            DropDownButton downButton = (DropDownButton)sender;
            downButton.ShowDropDown();
        }

        /// <summary>
        /// 按钮的点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dropDownButton5_Click(object sender, EventArgs e)
        {
            actionButton.BringToFront();
            DropDownButton downButton = (DropDownButton)sender;
            downButton.ShowDropDown();
        }

        private void dropDownButton4_Click(object sender, EventArgs e)
        {
            dropDownButton4.BringToFront();
            DropDownButton downButton = (DropDownButton)sender;
            downButton.ShowDropDown();
        }



        #region INotification接口
        //public void Receive(string channel, object content)
        //{
        //    if (content != null)
        //    {
        //        string PrimaryKeyValue = content.ToString();
        //        System.Data.DataTable data = this.Model.BaseTable;
        //        string PrimaryKey = this.Model.GetPrimaryName();
        //        //条件
        //        BaseEntity.Condition con = BaseEntity.Condition.Create(PrimaryKey, "=", "'" + PrimaryKeyValue.Replace("'", "''") + "'");
        //        string condition = con.ToString();
        //        Marmat.BaseEntity.IDocument document = Marmat.BaseModel.Env.Build(this.Model.GetName());

        //        System.Data.DataRow dataRow = data.Select(PrimaryKey + "='" + PrimaryKeyValue + "'").FirstOrDefault();
        //        //var result = document.Read(this.Fields, condition);
        //        var result = document.Read(this.Model.Columns.Select(x => x.Name).ToArray(), condition);
        //        if (result.Rows.Count == 1)
        //        {
        //            if (dataRow is null)
        //            {
        //                DataRow row = data.NewRow();
        //                foreach (DataColumn item in result.Rows[0].Table.Columns)
        //                {
        //                    row[item.ColumnName] = result.Rows[0][item.ColumnName];
        //                }
        //                data.Rows.Add(row);
        //            }
        //            else
        //            {
        //                //dataRow.ItemArray = result.Rows[0].ItemArray;
        //                foreach (DataColumn item in dataRow.Table.Columns)
        //                {
        //                    dataRow[item.ColumnName] = result.Rows[0][item.ColumnName];
        //                }
        //            }
        //            this.Model.ReadChildModel();
        //            data.AcceptChanges();
        //        }
        //        else if (dataRow != null)
        //        {
        //            data.Rows.Remove(dataRow);
        //        }
        //    }
        //}
        #endregion


        private void Panel3_Paint(object sender, PaintEventArgs e)
        {
            Control control = (Control)sender;
            using (Pen pen = new Pen(Localization.Colors.BorderColor))
            {
                e.Graphics.DrawLine(pen, 0, 0, control.Width, 0);
                e.Graphics.DrawLine(pen, 0, control.Height - 1, control.Width, control.Height - 1);
            }
        }

        /// <summary>
        /// 设置路由
        /// </summary>
        /// <param name="route"></param>
        public void SetRoute(IViewFormRoute route)
        {
            System.Windows.Forms.Control control = route.GetViewPanel();
            Foundation.IViewFormController controller = route.GetController();
            if (control is null)
                throw new ArgumentException($"{ nameof(route) }  的 {nameof(route.GetViewPanel)} 的返回值不能为 null。", nameof(route));
            // 移除之前的面板
            if (this.panel != null)
                this.Controls.Remove(this.panel);
            //if (controller is IViewRefresh viewRefresh)
            //{
            //    viewRefresh.Refresh = this.LoadData;
            //}
            control.TextChanged += Control_TextChanged;
            this.viewRoute = new DefaultViewFormRoute(controller, control);
            this.createButton.Visible = controller.AllowCreate;
            this.Text = string.IsNullOrEmpty(control.Text) ? control.Name : control.Text;

            //初始控件布局            
            if (control is System.Windows.Forms.Form frm)
            {
                if (frm.ShowIcon)
                    this.Icon = frm.Icon;
                this.ShowInTaskbar = frm.ShowInTaskbar;
                frm.TopLevel = false;
                frm.Parent = this;
                frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                frm.Show();
            }
            control.Dock = DockStyle.Fill;
            this.Controls.Add(control);
            this.panel = control;
            control.BringToFront();

            this.InitializeForm();
            this.InitializeSearchControl();
            #region 注释

            // todo 此处需要优化，需要支持多面板
            //if (this.Controller is IGetSelectedRows selected)
            //    selected.SelectionChanged += ViewForm_SelectionChanged;

            //if (this.Controller is IMultiView multi)
            //{
            //    var views = multi.GetViews();
            //    this.panel4.Visible = views.Length > 0;
            //    foreach (var view in views)
            //    {
            //        DevExpress.XtraEditors.CheckButton checkButton = new CheckButton();
            //        checkButton.ImageOptions.Image = view.Icon.ToBitmap();
            //        checkButton.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
            //        checkButton.Name = view.Name;
            //        checkButton.ToolTip = view.Name;
            //        checkButton.Dock = DockStyle.Right;
            //        checkButton.CheckedChanged += delegate (object sender, EventArgs e)
            //        {
            //            DevExpress.XtraEditors.CheckButton ct = (DevExpress.XtraEditors.CheckButton)sender;
            //            if (ct.Checked)
            //            {
            //                foreach (var item in ct.Parent.Controls)
            //                {
            //                    if (item != ct && item is DevExpress.XtraEditors.CheckButton child)
            //                        child.Checked = false;
            //                }
            //                multi.SwitchView(ct.Name);
            //            }
            //        };
            //        this.panel4.Controls.Add(checkButton);
            //        checkButton.Width = checkButton.Height;
            //    }
            //    if (this.panel4.Controls.Count > 0 && this.panel4.Controls[0] is DevExpress.XtraEditors.CheckButton checkbutton)
            //        checkbutton.Checked = true;
            //} 
            #endregion
        }

        /// <summary>
        /// 设置控制器
        /// </summary>
        /// <param name="controller"></param>
        public void SetController(Foundation.IViewFormController controller)
        {
            if (controller is Control == false)
                throw new Exception($"{nameof(controller)} 必须 继承于 System.Windows.Forms.Control。");
            if (controller is Control control)
            {
                DefaultViewFormRoute route = new DefaultViewFormRoute(controller, control);
                this.SetRoute(route);
            }
        }

        private void Control_TextChanged(object sender, EventArgs e)
        {
            if (sender is Control control)
            {
                this.Text = control.Text ?? "未定义";
            }
        }

        private void SearchControl_ValueChanged(object sender, EventArgs e)
        {
            var controller = this.viewRoute.GetController();
            if (controller is IViewFormPagination)
                pageControl1.LoadPage = 0;
            if (this.is_show)
            {
                this.LoadData();
            }
        }

        /// <summary>
        /// 分页控件的点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PageControl1_ItemClick(object sender, EventArgs e)
        {
            this.LoadData();
        }

        /// <summary>
        /// 初始化搜索
        /// </summary>
        private void InitializeSearchControl()
        {
            try
            {
                Control control = null;
                ISearchControl searchControl = null;
                Marmat.Forms.WindowsAPI.LockWindowUpdate(this.Handle.ToInt32());
                if (this.viewRoute.GetViewPanel() is ICustomSearchControl custom)
                {
                    searchControl = custom;
                    control = custom.GetSearchControl();
                }
                else
                {
                    searchControl = SystemCommand.GetService<Marmat.Foundation.ISearchControl>();
                    control = searchControl as System.Windows.Forms.Control;
                }

                //if (this.viewRoute.GetController() is IReceiveSearchControl receive)
                //    receive.SearchControl = searchControl;
                if (control != null || searchControl != null)
                {
                    control.Dock = DockStyle.Top;
                    this.Controls.Add(control);
                    control.SuspendLayout();
                    this.searchControl = searchControl;
                    this.searchControl.ValueChanged += this.SearchControl_ValueChanged;

                    Foundation.IViewFormController controller = this.viewRoute.GetController();
                    if (controller is ISearchControlController searchControlController)
                        searchControlController.InitializationSearchControl(searchControl);
                    //if (controller is ISearchControlCollection search)
                    //    BuildFilterGroupButton(search.SearchCollection());
                    //if (searchControl is ISearchControlController searchController)
                    //    searchController.Initialization(controller);
                }
            }
            finally
            {
                Marmat.Forms.WindowsAPI.LockWindowUpdate(IntPtr.Zero.ToInt32());
            }
        }

        ///// <summary>
        ///// 构建筛选组按钮
        ///// </summary>
        //private void BuildFilterGroupButton(SearchFieldCollection fieldCollection)
        //{
        //    DXPopupMenu searchs = new DXPopupMenu();
        //    foreach (var item in fieldCollection)
        //    {
        //        if (item is SearchControlItem field)
        //        {
        //            if (field.DataType == typeof(DateTime) || field.DataType == typeof(DateTime?))
        //            {
        //                string fieldName = field.Name;
        //                SearchControlGroup group = new SearchControlGroup();
        //                group.Name = field.Name;
        //                DevExpress.Utils.Menu.DXSubMenuItem menuItem = new DXSubMenuItem();
        //                menuItem.Caption = field.Caption ?? field.Name;
        //                Dictionary<string, string> dic = new Dictionary<string, string>
        //                {
        //                    ["过去7天"] = $"DATEDIFF(DAY,{fieldName},GETDATE()) <= 7",
        //                    ["过去30天"] = $"DATEDIFF(DAY,{fieldName},GETDATE()) <= 30",
        //                    ["过去365天内"] = $"DATEDIFF(DAY,{fieldName},GETDATE()) <= 365",
        //                    ["今日"] = $"DATEDIFF(DAY,{fieldName},GETDATE()) = 0",
        //                    ["本周"] = $"DATEDIFF(WEEK,{fieldName},GETDATE()) = 0",
        //                    ["本月"] = $"DATEDIFF(MONTH,{fieldName},GETDATE()) = 0",
        //                    ["本季度"] = $"DATEDIFF(QQ,{fieldName},GETDATE()) = 0",
        //                    ["本年度"] = $"DATEDIFF(YEAR,{fieldName},GETDATE()) = 0",
        //                    ["昨天"] = $"DATEDIFF(DAY,{fieldName},GETDATE()) = 1",
        //                    ["上周"] = $"DATEDIFF(WEEK,{fieldName},GETDATE()) = 1",
        //                    ["上月"] = $"DATEDIFF(MONTH,{fieldName},GETDATE()) = 1",
        //                    ["上季度"] = $"DATEDIFF(QQ,{fieldName},GETDATE()) = 1",
        //                    ["上一年"] = $"DATEDIFF(YEAR,{fieldName},GETDATE()) = 1"
        //                };
        //                foreach (var val in dic)
        //                {
        //                    SearchControlGroup itemGroup = new SearchControlGroup();
        //                    itemGroup.Name = val.Key;
        //                    itemGroup.Caption = (field.Caption ?? field.Name) + ":" + val.Key;
        //                    itemGroup.Condition = val.Value;
        //                    DXMenuItem button = new DXMenuItem();
        //                    button.Tag = itemGroup;
        //                    button.Caption = val.Key;
        //                    if (val.Key == "今日" || val.Key == "昨天")
        //                        button.BeginGroup = true;
        //                    button.Click += delegate (object sender, EventArgs e)
        //                    {
        //                        menuItem.Items.ToList().ForEach(x => x.ImageOptions.Image = null);
        //                        group.Condition = val.Value;
        //                        button.ImageOptions.Image = Properties.Resources.选择.GetThumbnailImage(20, 20, () => true, IntPtr.Zero);
        //                        group.Caption = (field.Caption ?? field.Name) + ":" + val.Key;
        //                        this.searchControl.Value.Add(group.Name);
        //                    };
        //                    menuItem.Items.Add(button);
        //                }
        //                searchs.Items.Add(menuItem);
        //            }
        //        }
        //        else if (item is ISearchControlGroup group)
        //        {
        //            DXMenuItem button = new DXMenuItem();
        //            button.Tag = group;
        //            button.Caption = string.IsNullOrEmpty(group.Caption) ? group.Name : group.Caption;
        //            button.Click += Button_Click;
        //            searchs.Items.Add(button);
        //        }
        //    }
        //    this.dropDownButton1.DropDownControl = searchs;
        //    this.dropDownButton1.Visible = searchs.Items.Count > 0;
        //}

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (sender is Timer timer)
            {
                timer.Enabled = false;
                this.LoadData();
                timer.Dispose();
            }
        }

        /// <summary>
        /// 开启批量编辑
        /// </summary>
        /// <param name="item"></param>
        public void OpenBatchOperation(IButtonItem item)
        {
            this.batchPane.Open();
            Marmat.Forms.WindowsAPI.LockWindowUpdate(this.Handle.ToInt32());
            panel1.Visible = false;
            flowLayoutPanel1.Visible = false;
            batchActionPanel.Visible = true;
            batchButton = item;
            Marmat.Forms.WindowsAPI.LockWindowUpdate(IntPtr.Zero.ToInt32());
        }

        /// <summary>
        /// 取消选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            this.batchPane.Close();
            Marmat.Forms.WindowsAPI.LockWindowUpdate(this.Handle.ToInt32());
            panel1.Visible = true;
            flowLayoutPanel1.Visible = true;
            batchActionPanel.Visible = false;
            batchButton = null;
            Marmat.Forms.WindowsAPI.LockWindowUpdate(IntPtr.Zero.ToInt32());
        }

        /// <summary>
        /// 批量执行选中的记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            try
            {
                Foundation.IViewFormController controller = this.viewRoute.GetController();
                var collection = this.batchPane.GetSelectionCollection();
                if (controller is IViewFormBatchAction action)
                    action.ButtonClick(this.batchButton, collection.Cast<object>().ToArray());
            }
            finally
            {
                this.batchPane.Close();
                Marmat.Forms.WindowsAPI.LockWindowUpdate(this.Handle.ToInt32());
                panel1.Visible = true;
                flowLayoutPanel1.Visible = true;
                batchActionPanel.Visible = false;
                batchButton = null;
                Marmat.Forms.WindowsAPI.LockWindowUpdate(IntPtr.Zero.ToInt32());
            }
        }

        /// <summary>
        /// 批量执行全部的记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            try
            {
                Foundation.IViewFormController controller = this.viewRoute.GetController();
                var collection = this.batchPane.GetAllCollection();
                if (controller is IViewFormBatchAction action)
                    action.ButtonClick(this.batchButton, collection.Cast<object>().ToArray());
            }
            finally
            {
                this.batchPane.Close();
                Marmat.Forms.WindowsAPI.LockWindowUpdate(this.Handle.ToInt32());
                panel1.Visible = true;
                flowLayoutPanel1.Visible = true;
                batchActionPanel.Visible = false;
                batchButton = null;
                Marmat.Forms.WindowsAPI.LockWindowUpdate(IntPtr.Zero.ToInt32());
            }
        }

        private void panel1_SizeChanged(object sender, EventArgs e)
        {
            var control = this.pageControl1;
            control.Left = this.panel1.Right + 3;
            control.Width = control.Parent.Width - control.Left;
        }

        void INotification.ReceiveNotification(string channel, params object[] arguments)
        {
            ReceiveNotification(channel, arguments);
        }

        protected virtual void ReceiveNotification(string channel, params object[] arguments)
        {
            if (this.viewRoute.GetController() is INotification notification)
                notification.ReceiveNotification(channel, arguments);
        }
    }
}
